package com.ruoyi.cms.docs.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.cms.folder.domain.CmsFolder;
import com.ruoyi.cms.folder.service.ICmsFolderService;
import com.ruoyi.cms.utils.ConvertFileSize;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.cms.docs.domain.CmsDocs;
import com.ruoyi.cms.docs.service.ICmsDocsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 文件Controller
 * 
 * @author ning
 * @date 2023-06-25
 */
@RestController
@RequestMapping("/cms/docs")
public class CmsDocsController extends BaseController
{
    @Autowired
    private ICmsDocsService cmsDocsService;

    @Autowired
    private ICmsFolderService cmsFolderService;

    /**
     * 查询文件列表
     */
    @PreAuthorize("@ss.hasPermi('cms:docs:list')")
    @GetMapping("/list")
    public TableDataInfo list(CmsDocs cmsDocs)
    {
        startPage();
        List<CmsDocs> list = cmsDocsService.selectCmsDocsList(cmsDocs);
        for (CmsDocs docs : list) {
            String folderPath = getFolderPath(docs.getFolderId());
            docs.setFolderPath(folderPath);
            // 文件大小计算
            BigDecimal bigDecimal = new BigDecimal(docs.getContentSize());
            String size = ConvertFileSize.getNetFileSizeDescription(bigDecimal.longValue());
            docs.setContentSize(size);
        }
        return getDataTable(list);
    }

    /**
     * 导出文件列表
     */
    @PreAuthorize("@ss.hasPermi('cms:docs:export')")
    @Log(title = "文件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmsDocs cmsDocs)
    {
        List<CmsDocs> list = cmsDocsService.selectCmsDocsList(cmsDocs);
        ExcelUtil<CmsDocs> util = new ExcelUtil<CmsDocs>(CmsDocs.class);
        util.exportExcel(response, list, "文件数据");
    }

    /**
     * 获取文件详细信息
     */
    @PreAuthorize("@ss.hasPermi('cms:docs:query')")
    @GetMapping(value = "/{docsId}")
    public AjaxResult getInfo(@PathVariable("docsId") Long docsId)
    {
        return success(cmsDocsService.selectCmsDocsByDocsId(docsId));
    }

    /**
     * 新增文件
     */
    @PreAuthorize("@ss.hasPermi('cms:docs:add')")
    @Log(title = "文件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmsDocs cmsDocs)
    {
        cmsDocs.setCreateBy(getUsername());
        return toAjax(cmsDocsService.insertCmsDocs(cmsDocs));
    }

    /**
     * 修改文件
     */
    @PreAuthorize("@ss.hasPermi('cms:docs:edit')")
    @Log(title = "文件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmsDocs cmsDocs)
    {
        cmsDocs.setUpdateBy(getUsername());
        return toAjax(cmsDocsService.updateCmsDocs(cmsDocs));
    }

    /**
     * 删除文件
     */
    @PreAuthorize("@ss.hasPermi('cms:docs:remove')")
    @Log(title = "文件", businessType = BusinessType.DELETE)
	@DeleteMapping("/{docsIds}")
    public AjaxResult remove(@PathVariable Long[] docsIds)
    {
        return toAjax(cmsDocsService.deleteCmsDocsByDocsIds(docsIds));
    }

    private String getFolderPath(Long folderId) {
        StringBuilder pathBuilder = new StringBuilder("我的桌面");
        CmsFolder folder = cmsFolderService.selectCmsFolderByFolderId(folderId);
        String ancestors = folder.getAncestors();
        String[] ancestorIds = ancestors.split(",");
        List<Long> ids = new ArrayList();
        for (String id : ancestorIds) {
            ids.add(Long.parseLong(id));
        }
        // 添加它自己的id
        ids.add(folder.getFolderId());
        List<CmsFolder> cmsFolders = cmsFolderService.selectCmsFolderListByAncestor(ids);
        // 根据id字段，把List转换为Map
        Map<Long, CmsFolder> folderMap = cmsFolders.stream().collect(Collectors.toMap(CmsFolder::getFolderId, Function.identity()));
        for (Long id : ids) {
            CmsFolder cmsFolder = folderMap.get(id);
            if (ObjectUtils.isNotEmpty(cmsFolder)){
                pathBuilder.append("/").append(cmsFolder.getFolderName());
            }
        }
        return pathBuilder.toString();
    }
}
